import { BaseTable, utils, InputEditor, NumberView } from '@/components/BaseTable';
import { showConfirm } from '@/utils/utils';
import { Button, Col, Icon, message, Radio, Row, Tabs, Tooltip, Popover, Table } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import React, { useState, useMemo } from 'react';
import * as api from '@/services/ReturnMoneyPlanMgr';
import { router } from 'umi';
import { countAllPeriodVal, modifyRowData, verificationSaveParams } from '../utils/publicMethod';

const PopoverComponent = props => {
  const columns = useMemo(
    () => [
      {
        key: 'name',
        title: '业态产品',
        width: 200,
        render: rows => {
          const name = `${rows?.productName}-${rows?.proTypeName}-${rows?.freeTypeName}-${rows?.businessTypeName}`;
          return (
            <div className="ellipsis">
              <Tooltip placement="topLeft" title={name}>
                {name}
              </Tooltip>
            </div>
          );
        },
      },
      {
        key: 'finalReceivable',
        title: '期末应收',
        width: 110,
        align: 'right',
        render: rows => <NumberView cellData={rows?.finalReceivable / 10000} precision={4} />,
      },
    ],
    [],
  );

  return (
    <Table
      size="small"
      columns={columns}
      dataSource={props?.lastList}
      pagination={false}
      scroll={{ y: 200, x: 310 }}
      bordered
    />
  );
};

export default function EditContent(props) {
  const {
    supplyDates,
    currentYear,
    currentMonth,
    dispatch,
    preservationList,
    latestYearMonth,
    affiliationMonth,
    treeData,
    isEdit,
  } = props;

  const [saveLoading, setSaveLoading] = useState(false);
  const titleTree = [
    {
      name: '业态产品',
      key: 'name',
      colspan: 1,
      rowspan: 2,
      frozen: 'left',
    },
    {
      name: (
        <div style={{ textAlign: 'center' }}>
          <div>本期签约</div>
          <div>(金额)</div>
        </div>
      ),
      key: 'signAmount',
      colspan: 1,
      rowspan: 2,
    },
    {
      name: '实际数 (金额)',
      key: 'Actual',
      colspan: 2,
      rowspan: 1,
    },
    {
      name: '测算数 (金额)',
      key: 'Calculate',
      colspan: 2,
      rowspan: 1,
    },
    {
      name: '调整数 (金额)',
      key: 'Adjust',
      colspan: 2,
      rowspan: 1,
      hidden: !isEdit,
    },
    {
      name: (
        <div style={{ textAlign: 'center' }}>
          <div>已签未回</div>
          <div>回款数</div>
          <div>(金额)</div>
        </div>
      ),
      key: 'signedUnrecovered',
      colspan: 1,
      rowspan: 2,
    },
    {
      name: (
        <div style={{ textAlign: 'center' }}>
          <div>期初应退</div>
          <div>回款数</div>
          <div>(金额)</div>
        </div>
      ),
      key: 'refundable',
      colspan: 1,
      rowspan: 2,
    },
    {
      name: '本期回款 (金额)',
      key: 'ReturnAmount',
      colspan: 4,
      rowspan: 1,
    },
    {
      name: '回款率 (%)',
      key: 'Rate',
      colspan: 2,
      rowspan: 1,
    },
  ];

  // 监听输入值的变化
  const changeIptVal = (val, key, id) => {
    const modifyAfterData = modifyRowData({
      list: preservationList,
      yearMonth: `${currentYear}-${currentMonth}`,
      val: val * 10000,
      key,
      id,
    });

    dispatch({
      type: 'ReturnMoneyPlanEdit/onChangeVal',
      payload: { modifyAfterData, id },
    });
  };

  const fixedColumns = [
    {
      key: 'name',
      dataKey: 'name',
      width: 200,
      frozen: 'left',
      cellRenderer: ({ rowData }) => {
        const name = `${rowData.productName}-${rowData.proTypeName}-${rowData.freeTypeName}-${rowData.businessTypeName}`;
        return (
          <div className="ellipsis">
            <Tooltip placement="topLeft" title={name}>
              {name}
            </Tooltip>
          </div>
        );
      },
    },
    // 本期签约
    {
      key: 'signAmount',
      dataKey: 'signAmount',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    // 实际数
    {
      key: 'incrementReturnAmountActual',
      dataKey: 'incrementReturnAmountActual',
      title: '增量回款',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    {
      key: 'storeReturnAmountActual',
      dataKey: 'storeReturnAmountActual',
      title: '存量回款',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    // 测算数
    {
      key: 'incrementReturnAmountCalculate',
      dataKey: 'incrementReturnAmountCalculate',
      title: '增量回款',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    {
      key: 'storeReturnAmountCalculate',
      dataKey: 'storeReturnAmountCalculate',
      title: '存量回款',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    // 调整数
    {
      key: 'incrementReturnAmountAdjust',
      dataKey: 'incrementReturnAmountAdjust',
      title: '增量回款',
      align: 'right',
      width: 110,
      hidden: !isEdit,
      cellRenderer: ({ rowData }) => {
        if (moment(affiliationMonth).isSameOrBefore(`${currentYear}-${currentMonth}`)) {
          return (
            <InputEditor
              precision={4}
              size="small"
              cellData={rowData.incrementReturnAmountAdjust}
              validateStatus={rowData.errorIncrement}
              onChange={val =>
                changeIptVal(val, 'incrementReturnAmountAdjust', rowData.combinationProductCode)
              }
              min={-999999999999}
            />
          );
        }
        return rowData.incrementReturnAmountAdjust;
      },
    },
    {
      key: 'storeReturnAmountAdjust',
      dataKey: 'storeReturnAmountAdjust',
      title: '存量回款',
      align: 'right',
      width: 110,
      hidden: !isEdit,
      cellRenderer: ({ rowData }) => {
        if (moment(affiliationMonth).isSameOrBefore(`${currentYear}-${currentMonth}`)) {
          return (
            <InputEditor
              // disabled={rowData.storeReturnAmountCalculate === 0}
              precision={4}
              size="small"
              cellData={rowData.storeReturnAmountAdjust}
              validateStatus={rowData.errorStock}
              onChange={val =>
                changeIptVal(val, 'storeReturnAmountAdjust', rowData.combinationProductCode)
              }
              min={-999999999999}
            />
          );
        }
        return rowData.incrementReturnAmountAdjust;
      },
    },
    // 已签未回
    {
      key: 'signedUnrecovered',
      dataKey: 'signedUnrecovered',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    // 期初应退
    {
      key: 'refundable',
      dataKey: 'refundable',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    // 本期回款
    {
      key: 'incrementReturnAmount',
      dataKey: 'incrementReturnAmount',
      title: '增量回款',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    {
      key: 'storeReturnAmount',
      dataKey: 'storeReturnAmount',
      title: '存量回款',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    {
      key: 'totalReturnAmount',
      dataKey: 'totalReturnAmount',
      title: '回款合计',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    {
      key: 'finalReceivable',
      dataKey: 'finalReceivable',
      title: '期末应收',
      align: 'right',
      width: 110,
      cellRenderer: data => <NumberView {...data} precision={4} />,
    },
    // 回款率
    {
      key: 'signReturnRate',
      dataKey: 'signReturnRate',
      title: '累计签约回款率',
      align: 'right',
      width: 110,
      cellRenderer: ({ rowData }) => `${rowData.signReturnRate.toFixed(3)}%`,
    },
    {
      key: 'annualOverallReturnRate',
      dataKey: 'annualOverallReturnRate',
      title: '年度综合回款率',
      align: 'right',
      width: 110,
      cellRenderer: ({ rowData }) => `${rowData.annualOverallReturnRate.toFixed(3)}%`,
    },
  ];

  const headerRenderer = utils.getHeaderRenderer(titleTree, 1);

  // 编辑年
  const handlerEditYear = (targetKey, actionType) => {
    dispatch({
      type: 'ReturnMoneyPlanEdit/editYear',
      payload: {
        targetKey,
        actionType,
      },
    });
  };
  // 监听年月
  const onChangeYearMonth = (val, key) => {
    dispatch({
      type: 'ReturnMoneyPlanEdit/onChangeYearMonth',
      payload: {
        key,
        val,
      },
    });
  };

  const { returnAmountTotal, finalReceivableTotal, isSave, lastList } = countAllPeriodVal(
    preservationList,
    latestYearMonth,
  );

  // handlerSubMit 保存
  const handlerSubMit = () => {
    showConfirm(
      () => {
        setSaveLoading(true);
        const cloneList = _.cloneDeep(preservationList);
        const data = [];
        _.forEach(cloneList, rowData => {
          // data.push({detailList});
          data.push({
            detailList: verificationSaveParams(rowData.detailList),
          });
        });
        console.log(data, 'cloneList 删除后要传的数据');
        api.editSaveUsingPUT({ data }).then(res => {
          if (res && res.code === 1) {
            message.success('保存成功', 1, () => {
              const { level1, level2, project, stage, version, category } = props.match.params;
              router.push(
                `/OperatingPlan/ReturnMoneyPlan/${level1}/${level2}/${project}/${stage}/${category}/${version}`,
              );
            });
          }
          setSaveLoading(false);
        });
      },
      '确定要保存回款计划？',
      '',
    );
  };

  // 取消返回
  const handlerCancelReturn = () => {
    showConfirm(
      () => {
        const { level1, level2, project, stage, version, category } = props.match.params;
        router.push(
          `/OperatingPlan/ReturnMoneyPlan/${level1}/${level2}/${project}/${stage}/${category}/${version}`,
        );
      },
      '确定要取消编辑？',
      '取消后本次编辑内容将不保存。',
    );
  };

  return (
    <div>
      <Row type="flex" justify="space-between" align="middle">
        <Col>
          <h3>编制回款计划</h3>
        </Col>
        <Col className="color-red" style={{ display: 'flex' }}>
          组团全周期回款金额：
          {<NumberView cellData={returnAmountTotal / 10000} precision={4} />} 万元，期末应收金额：
          {<NumberView cellData={finalReceivableTotal / 10000} precision={4} />}万元 &nbsp;&nbsp;
          <Popover content={<PopoverComponent lastList={lastList} />} placement="bottom">
            <a>详情</a>
          </Popover>
        </Col>
      </Row>
      <Row type="flex" justify="space-between" align="middle">
        <Col span={24}>
          <Tabs
            onChange={val => onChangeYearMonth(val, 'currentYear')}
            activeKey={`${currentYear}`}
            type="editable-card"
            animated={false}
            onEdit={handlerEditYear}
            hideAdd
            tabBarExtraContent={
              <Button
                type="primary"
                onClick={() => handlerEditYear(null, 'add')}
                disabled={_.isEmpty(supplyDates)}
              >
                添加年
              </Button>
            }
          >
            {supplyDates.map(pane => (
              <Tabs.TabPane
                tab={
                  <span style={pane.isEdit ? { color: '#2761FF', textAlign: 'center' } : {}}>
                    {pane.isEdit ? <Icon type="edit" /> : ''}
                    {pane.title}
                  </span>
                }
                key={pane.title}
                closable={pane.closable}
              >
                <Radio.Group
                  value={Number(currentMonth)}
                  buttonStyle="solid"
                  className="month12"
                  onChange={ev => onChangeYearMonth(ev.target.value, 'currentMonth')}
                >
                  {pane.monthList.map(m => (
                    <Radio.Button key={`${m.value}`} disabled={m.disabled} value={m.value}>
                      <span style={m.isEdit ? { color: '#2761FF', textAlign: 'center' } : {}}>
                        {m.isEdit && <Icon type="edit" />}&nbsp;{m.value}月
                      </span>
                    </Radio.Button>
                  ))}
                </Radio.Group>
              </Tabs.TabPane>
            ))}
          </Tabs>
        </Col>
        <Col span={24}>
          <BaseTable
            subtractHeight="325px"
            expandColumnKey="id"
            headerHeight={[30, 30]}
            fixedColumns={fixedColumns}
            headerRenderer={headerRenderer}
            treeData={treeData}
          />
        </Col>
        <Col span={24} style={{ display: 'flex', justifyContent: 'center', marginTop: 10 }}>
          <Button
            type="primary"
            style={{ margin: '0 2.5px' }}
            onClick={handlerSubMit}
            disabled={isSave}
            loading={saveLoading}
          >
            保存
          </Button>
          <Button style={{ margin: '0 2.5px' }} onClick={handlerCancelReturn}>
            取消
          </Button>
        </Col>
      </Row>
    </div>
  );
}
